package cn.edu.util;

import java.sql.*;

public class DBUtil {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/db_group?serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PWD = "123456";

    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取一个连接数据的对象
     * @return 当前程序的连接数据库对象
     */
    public static Connection getConnection(){
        Connection conn = null ;
        try {
             conn = DriverManager.getConnection(URL,USER,PWD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 为update语句实现的关闭方法
     * @param conn
     * @param stat
     */
    public static void close(Connection conn , Statement stat ){
        try {
            stat.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 为query语句实现关闭的方法
     * @param conn
     * @param stat
     * @param rs
     */
    public static void close(Connection conn , Statement stat , ResultSet rs){
        try {
            rs.close();
            stat.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static int update(String sql ,Object... objs) throws SQLException {
//      String sql1 = "insert into tb_user (name,password)values(?,?);";
        Connection conn = getConnection();
        PreparedStatement prestat = conn.prepareStatement(sql);
        for (int i = 0 ;i<objs.length;i++) {
            prestat.setObject(i+1,objs[i]);
        }
        int i = prestat.executeUpdate();
        System.out.println(i);
        close(conn,prestat);
        return i ;
    }


}
